package com.cj.services;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cj.Mapper.CoinMapper;
import com.cj.Mapper.CoinlogMapper;
import com.cj.models.UserCoinLogModel;
import com.cj.models.UserCoinModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@DS("crdDS")
public class CoinService {

    @Autowired
    CoinMapper coinMapper;

    @Autowired
    CoinlogMapper coinlogMapper;

    //转账方法
    @Transactional(rollbackFor = Exception.class)
    public boolean transfer(String from,String to,int coin) throws Exception {
        int ret1 = this.coinMapper.transferFrom(from,coin);
        int ret2 = this.coinMapper.transferTo(to,coin);

        this.coinMapper.waitSecond(3);
        if(ret1==1 && ret2 ==1){
            int ret3=this.coinlogMapper.insert(new UserCoinLogModel(){//记日志
                {
                    setLogTime(new Date());
                    setLogNote("转账");
                    setToUser(to);
                    setFromUser(from);
                    setCoin(coin);
                }
            });
            if(ret3==1){
                return true;
            }
        }else {
            throw new Exception("转账失败");
        }
        return false;
    }

    //获取用户虚拟币方法 悲观锁
    public int getUserCoin(String userName){
        QueryWrapper<UserCoinModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);
        queryWrapper.last("for update");
        //select * from xxx where username for update
        UserCoinModel userCoinModel = this.coinMapper.selectOne(queryWrapper);
        if(userCoinModel==null){
            return 0;
        }else {
            return userCoinModel.getCoin();
        }
    }

    //获取用户虚拟币方法 乐观锁
    public UserCoinModel getUserCoinForModel(String userName){
        QueryWrapper<UserCoinModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);

        return this.coinMapper.selectOne(queryWrapper);

    }

    public int updateVersion(String userName,int version){
        return this.coinMapper.updateVersion(userName,version);
    }




}
